package eerbaar.shared.persist.internal.lib;

import java.util.ArrayList;
import java.util.List;

import eerbaar.context.IParam;
import eerbaar.context.IParams;
import eerbaar.context.ParamFactory;
import eerbaar.shared.exceptions.GameException;
import eerbaar.shared.exceptions.GameRuntimeException;
import eerbaar.shared.persist.IPersistService;
import eerbaar.shared.persist.IPersister;
import eerbaar.shared.persist.ISaver;
import eerbaar.shared.service.ServiceFactory;
import eerbaar.shared.tree.INode;
import eerbaar.shared.tree.NodeCmdFactory;

public class ParamsPersister implements IPersister<IParams> {

    public static final String NAME = "params";

    private IParams target;

    public ParamsPersister() {
        //
    }

    public ParamsPersister(INode node) throws GameRuntimeException {
        load(node);
    }

    public ParamsPersister(IParams wrapper) {
        this.target = wrapper;
    }

    @Override
    public Class<IParams> getRegistertedInterface() {
        return IParams.class;
    }

    @Override
    public ISaver<?>[] getSavableChildren() {

        List<ParamPersister> result = new ArrayList<ParamPersister>();

        IParam[] params = this.target.getParamArray();
        for (IParam e : params) {
            ParamPersister p = new ParamPersister(e);
            result.add(p);
        }

        return result.toArray(new ParamPersister[] {});
    }

    @Override
    public String getSavableName() {

        return NAME;
    }

    @Override
    public IParams getTarget() {
        return this.target;
    }

    @Override
    public boolean isAssignableFrom(ISaver<?> savable) {
        return false;
    }

    @Override
    public IParams load(INode node) {
        assert (node != null);

        IParams result = ParamFactory.createParams();

        IPersistService service = ServiceFactory
                .getService(IPersistService.class);

        List<INode> list = NodeCmdFactory.findChildren(node,
                ParamPersister.NAME);
        for (INode n : list) {
            try {
                IParam obj = service.load(IParam.class, n);
                result.set(obj.getName(), obj.getValue());
            } catch (GameException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    @Override
    public void saveAttributes(INode node) {
        //
    }

    @Override
    public void setTarget(IParams obj) {
        this.target = obj;
    }

}
